'use strict';
const uniID = require('uni-id-common')
const ASE= require('ase')
exports.main = async (event, context) => {
	const db = uniCloud.databaseForJQL({
		event,
		context
	});
	const uniIDIns = uniID.createInstance({
		context: context,
	})
	const res = await uniIDIns.checkToken(event.uniIdToken)
	function random_str() {
		var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
			'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
			'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
			'U', 'V', 'W', 'X', 'Y', 'Z'
		];
		var random = [];
		for (var i = 0; i < 5; i++) {
			random.push(arr[Math.floor(Math.random() * 61)])
		}
		return random.join("");
	}
	event=JSON.parse(ASE.AES.decrypt(event.data,'yclycl1314520520','9740022097400220'))
	var random;
	const urldata = await db.collection("link").where({
		item_id: event.item_id
	}).get();
	if(urldata.data.length>0){
		return {
			to:"http://x2.ink/"+urldata.data[0].index
		}
	}else{
		while (true) {
			random = random_str()
			const info = await db.collection("link").where({
				index: random
			}).get();
			if (info.data.length == 0) {
				break;
			}
		}
		await db.collection("link").add({
			title:event.title,
			index: random,
			item_id: event.item_id,
			user_id:res.uid,
			time:new Date()
		});
		//返回数据给客户端
		return {
				to:"http://x2.ink/"+random
			}
	}
};
